package com.cuckoo.cuckoo_app2.service;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import com.cuckoo.cuckoo_app2.MyApplication;
import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.SiteLinkApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.Imp.VersionControlApiImp;
import com.cuckoo.cuckoo_app2.apiAsync.SiteLinkApi;
import com.cuckoo.cuckoo_app2.apiAsync.VersionControlApi;
import com.cuckoo.cuckoo_app2.business.Imp.SiteLinkBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.UserBusinessImp;
import com.cuckoo.cuckoo_app2.business.Imp.VersionControlBusinessImp;
import com.cuckoo.cuckoo_app2.business.SiteLinkBusiness;
import com.cuckoo.cuckoo_app2.business.UserBusiness;
import com.cuckoo.cuckoo_app2.business.VersionControlBusiness;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.dao.User;
import com.cuckoo.cuckoo_app2.dao.VersionControl;
import com.cuckoo.cuckoo_app2.model.IntentResponseModel;
import com.cuckoo.cuckoo_app2.utils.DialogUtils;
import com.cuckoo.cuckoo_app2.utils.LocalBroadCodeUtils;
import com.cuckoo.cuckoo_app2.utils.MessageCodeUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NetUpdateService {

    private Gson gson;
    private SiteLinkApi siteLinkApi;
    private VersionControlApi versionControlApi;
    private VersionControlBusiness versionControlBusiness;

    public NetUpdateService() {
        this.siteLinkApi = new SiteLinkApiImp();
        this.versionControlApi = new VersionControlApiImp();
        this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        this.versionControlBusiness = new VersionControlBusinessImp();
    }

    /**
     * 获取版本
     */
    public void getVersion() {
        User user = MyApplication.getInstances().getUser();
        if (user == null || user.getId().isEmpty()) {
            return;
        }

        versionControlApi.VersionListAsync(new BaseCallbac<JsonObject>() {

            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    return;
                }

                Map<String, VersionControl> versionMap = MyApplication.getInstances().getVersionControl();
                JsonArray result = data.getAsJsonArray("result");

                Map<String, VersionControl> newVersionControls = new HashMap<>();
                VersionControl versionControl;
                for (int i = 0; i < result.size(); i++) {
                    versionControl = gson.fromJson(result.get(i), VersionControl.class);
                    newVersionControls.put(versionControl.getName(), versionControl);
                }

                Map<String, Object> item;
                for (int i = 0; i < result.size(); i++) {
                    versionControl = gson.fromJson(result.get(i), VersionControl.class);
                    //更新不同版本
                    String name = versionControl.getName();
                    String valeu = versionControl.getValue();

                    if (versionMap == null || versionMap.getOrDefault(name, null) == null) {
                        versionControlBusiness.insert(versionControl);
                    }

                    boolean isUpdate = updataVersionMap(name, valeu, newVersionControls);
                    if (isUpdate) {
                        versionControlBusiness.update(versionControl);
                    }
                }

                // 清除版本缓存
                MyApplication.getInstances().clearVersionControl();
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });
    }

    /**
     * 根据不同的名称更新对应的版本
     *
     * @param name
     */
    public boolean updataVersionMap(String name, String valeu, Map<String, VersionControl> newVersionControls){
        Map<String, VersionControl> versionMap = MyApplication.getInstances().getVersionControl();
        if (versionMap == null || versionMap.get(name) == null) {
            return false;
        }
        VersionControl versionControl = versionMap.get(name);
        switch (name) {
            case "SiteLinkVersion": // 平台列表版本 SiteLinkVersion
                if (versionControl.getValue().equals(valeu)) {
                    return false;
                }
                updateBackgroundData();
                return true;
            case "AppDownload":
                return true;
            case "AppVersion": //平台版本是否需要更新
                // 固定版本
                String appVersion = MyApplication.getInstances().getAppVersion();
                if (appVersion.equals(valeu)) {
                    return false;
                }

                VersionControl control = newVersionControls.get("AppDownload");
                LocalBroadCodeUtils.sendLocalBroadcast(
                        MyApplication.getInstances().getContext(),
                        LocalBroadCodeUtils.LOCAL_BROADCAST_UPDATE_APP,
                        new IntentResponseModel(LocalBroadCodeUtils.LOCAL_BROADCAST_UPDATE_APP, control.getValue())
                );
                return true;
        }
        return false;
    }


    /**
     * 更新平台列表后台数据 SiteLinkVersion
     */
    public void updateBackgroundData() {
        User user = MyApplication.getInstances().getUser();
        if (user == null || user.getId().isEmpty()) {
            return;
        }
        siteLinkApi.SiteLinkListAsync(new BaseCallbac<JsonObject>() {
            @Override
            public void onSuccess(JsonObject data) {
                if (!data.get("success").getAsBoolean()) {
                    return;
                }
                JsonArray result = data.getAsJsonArray("result");
                List<SiteLink> links = new ArrayList<>();
                SiteLink link;

                for (int i = 0; i < result.size(); i++) {
                    link = gson.fromJson(result.get(i), SiteLink.class);
                    links.add(link);
                }

                SiteLinkBusiness siteLinkBusiness = new SiteLinkBusinessImp();
                siteLinkBusiness.updataAll(links);
            }

            @Override
            public void onFailure(String errorMessage) {

            }
        });
    }

}
